package com.zib.vread.downloadmanagedemo.Update;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.zib.vread.downloadmanagedemo.DownloadUtils.DownloadUtil;
import com.zib.vread.downloadmanagedemo.R;

import java.io.File;
import java.io.IOException;


/**
 * Created by vread on 2016/8/24.
 */
public class UpdateService extends Service {
    private static final int NOTIFICATION_ID = 1;
    private Context context = this;

    private static String url = "http://softfile.3g.qq.com:8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk";
    private File f = Environment.getExternalStorageDirectory();
    private File saveFile = new File(f, "zyb_1.apk");

    private DownloadUtil downloadUtil = null;
    private NotificationManager notificationManager = null;
    private Notification.Builder notificationBuilder = null;
    private LocalBinder binder = new LocalBinder();

    private boolean isStart = false;
    private int max;

    private NetChangeObserver observer = new NetChangeObserver() {
        @Override
        public void onConnect(NetWorkUtil.NetType type) {
            super.onConnect(type);
            switch (type) {
                case NETWORK_WIFI:
                    if (isStart) {
                        downloadUtil.start();
                    }
                    break;
                default:
                    downloadUtil.pause();
                    notificationBuilder.setContentTitle("下载已暂停，等待WIFI环境");
                    notificationManager.notify(NOTIFICATION_ID, notificationBuilder.getNotification());
                    break;
            }
        }

        @Override
        public void onDisConnect() {
            super.onDisConnect();
            downloadUtil.pause();
            notificationBuilder.setContentTitle("下载已暂停，等待WIFI环境");
            notificationManager.notify(NOTIFICATION_ID, notificationBuilder.getNotification());
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        downloadUtil = new DownloadUtil(2, f.getPath(), "zyb_1.apk", url, this);
        NetworkStateReceiver.registerNetworkStateReceiver(this);
        NetworkStateReceiver.registerObserver(observer);
        if (!saveFile.exists()) {
            try {
                saveFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void showNotification() {
        if (notificationManager == null) {
            notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        }
        String text = "下载中,请稍后...";
        notificationBuilder = new Notification.Builder(this);
        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
        notificationBuilder.setTicker(text);
        notificationBuilder.setWhen(System.currentTimeMillis());
        notificationBuilder.setContentText(text);
        notificationBuilder.setContentTitle("正在下载更新" + 0 + "%");
        notificationBuilder.setProgress(100, 0, false);
        notificationBuilder.setOngoing(true);
        notificationBuilder.setAutoCancel(true);
        Notification notification = notificationBuilder.getNotification();
        startForeground(NOTIFICATION_ID, notification);
    }

    public void downloadApk() {
        downloadUtil.setOnDownloadListener(new DownloadUtil.OnDownloadListener() {
            @Override
            public void downloadStart(int fileSize) {
                max = fileSize;
            }

            @Override
            public void downloadProgress(int downloadedSize) {
                notificationBuilder.setContentTitle("正在下载更新" + (int) (downloadedSize * 100 / max) + "%");
                notificationBuilder.setProgress(100, (int) (downloadedSize * 100 / max), false);
                notificationManager.notify(NOTIFICATION_ID, notificationBuilder.getNotification());
            }

            @Override
            public void downloadEnd() {
                notificationBuilder.setContentTitle("下载完成");
                notificationBuilder.setProgress(0, 0, false);
                notificationManager.notify(NOTIFICATION_ID, notificationBuilder.getNotification());
                installApk(saveFile, context);
            }
        });
        downloadUtil.start();
        isStart = true;
    }

    public void installApk(File file, Context context) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        NetworkStateReceiver.unRegisterNetworkStateReceiver(this);
        if (observer != null) {
            NetworkStateReceiver.removeRegisterObserver(observer);
        }
    }

    public class LocalBinder extends Binder {
        public UpdateService getService() {
            return UpdateService.this;
        }
    }
}
